package com.wangrui.test;

import com.wangrui.entity.User;
import com.wangrui.entity.User4;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyBatisTest04 {

    /**
     * 获得MyBatis SqlSessionFactory
     * SqlSessionFactory负责创建SqlSession，一旦创建成功，就可以用SqlSession实例来执行映射语句
     * ，commit，rollback，close等方法。
     *
     * @return
     */
    private static SqlSessionFactory getSessionFactory() {
        SqlSessionFactory sessionFactory = null;
        String resource = "configuration.xml";
        try {
            sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));
        } catch (IOException e) {

            e.printStackTrace();
        }
        return sessionFactory;
    }

    /**
     * 不使用代理，直接使用mapper.xml
     */
    @Test
    public void testSelect() {
        //默认是手动提交的
        SqlSession sqlSession = getSessionFactory().openSession();

        String statement = "com.myBatis.userMapper4.findById";
        User4 user = sqlSession.selectOne(statement, 1);
        System.out.println(user);
    }

    /**
     * 多个参数，用hashMap
     */
    @Test
    public void testMultiParam() {
        //默认是手动提交的
        SqlSession sqlSession = getSessionFactory().openSession();
        String statement = "com.myBatis.userMapper4.findByMultiParam";
        Map<String,Object> parameter = new HashMap<>();
        parameter.put("age",23);
        parameter.put("name","wangrui");
        List<User> userList = sqlSession.selectList(statement, parameter);
        System.out.println(userList);
    }
}
